﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace FTBS.Controllers
{
    public class StaffController : Controller
    {
        private UserBLO _userBLO = new UserBLO();

        /// <summary>
        /// display all staffs
        /// </summary>
        /// <returns>list of staffs</returns>
        /// <author>hungph</author>
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            List<User> listStaff = new List<User>();
            listStaff = _userBLO.DisplayAllStaffs();
            ViewBag.NameSortParm = "fullname_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {
                listStaff = listStaff.Where(staff => staff.FullName.ToUpper().Contains(searchString.ToUpper())
                                                  || staff.Email.ToUpper().Contains(searchString.ToUpper())
                                                  || staff.PhoneNumber.ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "fullname_desc":
                    if (isSortDescending == true)
                    {
                        listStaff = listStaff.OrderByDescending(staff => staff.FullName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listStaff = listStaff.OrderBy(staff => staff.FullName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "email_desc":
                    if (isSortDescending == true)
                    {
                        listStaff = listStaff.OrderByDescending(staff => staff.Email).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listStaff = listStaff.OrderBy(staff => staff.Email).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "phoneNumber_desc":
                    if (isSortDescending == true)
                    {
                        listStaff = listStaff.OrderByDescending(staff => staff.PhoneNumber).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listStaff = listStaff.OrderBy(staff => staff.PhoneNumber).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "status_desc":
                    if (isSortDescending == true)
                    {
                        listStaff = listStaff.OrderByDescending(staff => staff.IsActive).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listStaff = listStaff.OrderBy(staff => staff.IsActive).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listStaff = listStaff.OrderBy(staff => staff.FullName).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listStaff.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// render View Create staff
        /// </summary>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Create()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            ViewBag.UserName = null;
            ViewBag.Email = null;

            List<String> listStrGender = new List<String>();
            listStrGender.Add("Nam");
            listStrGender.Add("Nữ");
            ViewBag.Gender = new SelectList(listStrGender);

            return View();
        }

        /// <summary>
        /// create staff
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        [HttpPost]
        public ActionResult Create(User user)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            if (_userBLO.CheckUsername(user))
            {
                ViewBag.UserName = user.UserName;
            }
            if (_userBLO.CheckEmail(user))
            {
                ViewBag.Email = user.Email;
            }
            if (ModelState.IsValid)
            {
                if (!_userBLO.CheckUsername(user) && !_userBLO.CheckEmail(user))
                {
                    user.Password = _userBLO.GenerateMD5(user.Password);
                    ViewBag.UserName = null;
                    ViewBag.Email = null;
                    _userBLO.CreateStaff(user);
                    return RedirectToAction("Index");
                }
            }

            List<String> listStrGender = new List<String>();
            listStrGender.Add("Nam");
            listStrGender.Add("Nữ");
            ViewBag.Gender = new SelectList(listStrGender);

            return View(user);
        }

        /// <summary>
        /// active staff
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Active(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            bool isActive = _userBLO.ActiveUser(user);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// deactive staff
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Deactive(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            bool isActive = _userBLO.DeactiveUser(user);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// load staff and render view edit info of staff
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Edit(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            List<String> listStrGender = new List<String>();
            if (user.Gender == "Nam")
            {
                listStrGender.Add("Nam");
                listStrGender.Add("Nữ");
            }
            else
            {
                listStrGender.Add("Nữ");
                listStrGender.Add("Nam");
            }
            ViewBag.Gender = new SelectList(listStrGender);
            return View(user);
        }

        /// <summary>
        /// edit info of staff
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            var email = _userBLO.LoadUserByUserName(user.UserName).Email;
            if (email == user.Email)
            {
                ViewBag.Email = null;
            }
            if (email != user.Email)
            {
                ViewBag.Email = user.Email;
            }
            if (ModelState.IsValid)
            {
                var isExist = _userBLO.CheckEmail(user);
                if (!isExist || (ViewBag.Email == null))
                {
                    user.Password = _userBLO.GenerateMD5(user.Password);
                    var isSuccess = _userBLO.EditStaff(user);
                    if (isSuccess)
                    {
                        ViewBag.Email = null;
                        return RedirectToAction("Index");
                    }
                }
            }
            List<String> listStrGender = new List<String>();
            if (user.Gender == "Nam")
            {
                listStrGender.Add("Nam");
                listStrGender.Add("Nữ");
            }
            else
            {
                listStrGender.Add("Nữ");
                listStrGender.Add("Nam");
            }
            ViewBag.Gender = new SelectList(listStrGender);
            return View(user);
        }

        /// <summary>
        /// Delete user
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Redirect to Index page</returns>
        /// <author>hungph</author>
        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            _userBLO.DeleteUser(user);
            return RedirectToAction("Index");
        }

        /// <summary>
        ///  Show staff detail
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>  
        /// <author>DuyHDV</author>  
        public ActionResult Detail(string id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User staff = _userBLO.LoadUserByUserName(id);
            return View(staff);
        }
        /// <summary>
        ///  Show staff profile
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>  
        /// <author>DuyHDV</author>  
        public ActionResult Profile()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            string id = Session["UserName"].ToString();
            User staff = _userBLO.LoadUserByUserName(id);
            return View(staff);
        }
        /// <summary>
        ///   Render edit profile page
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        /// <author>DuyHDV</author>   
        public ActionResult EditProfile(string id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            List<String> listStrGender = new List<String>();
            if (user.Gender == "Nam")
            {
                listStrGender.Add("Nam");
                listStrGender.Add("Nữ");
            }
            else
            {
                listStrGender.Add("Nữ");
                listStrGender.Add("Nam");
            }
            ViewBag.Gender = new SelectList(listStrGender);
            return View(user);
        }
        /// <summary>
        ///    Result page of the Edit action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>DuyHDV</author>  
        [HttpPost]
        public ActionResult EditProfile(User user, HttpPostedFileBase file)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            string username = user.UserName;
            User userData = _userBLO.LoadUserByUserName(username);
            if (user.Password == null)
            {
                user.Password = userData.Password;
            }
            List<String> listStrGender = new List<String>();
            if (user.Gender == "Nam")
            {
                listStrGender.Add("Nam");
                listStrGender.Add("Nữ");
            }
            else
            {
                listStrGender.Add("Nữ");
                listStrGender.Add("Nam");
            }
            bool isExisted = false;
            if (user.Email == userData.Email)
            {
                ViewBag.Email = null;
            }
            else
            {
                isExisted = _userBLO.CheckEmail(user);
                if(isExisted){                      
                ViewBag.Email = user.Email;
                }
            }
            if (ModelState.IsValid)
            {
                if (!isExisted && username == Session["UserName"].ToString())
                {
                    if (file != null)
                    {
                        if (file.FileName.Equals(userData.ImageURL))
                        {
                            file.SaveAs(HttpContext.Server.MapPath("~/Image/UserImages/") + file.FileName);
                            user.ImageURL = file.FileName;
                        }
                        else// if (!file.FileName.Equals(userData.ImageURL))
                        {
                            if (user.ImageURL != null)
                            {
                                System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/UserImages/") + userData.ImageURL);
                            }
                            file.SaveAs(HttpContext.Server.MapPath("~/Image/UserImages/") + file.FileName);
                            user.ImageURL = file.FileName;
                        }
                    }
                    else {
                        user.ImageURL = userData.ImageURL;
                    }
                    user.IsActive = userData.IsActive;
                    user.IsDeleted = userData.IsDeleted;
                    var isSuccess = _userBLO.EditStaff(user);
                    if (isSuccess)
                    {
                        this.Session["Account"] = user.FullName;
                        return RedirectToAction("Profile", new { id = username });
                    }
                }
            }
            ViewBag.Gender = new SelectList(listStrGender);
            return View(user);
        }
    }
}
